﻿using System;
using System.IO;
using System.Text;

namespace Zijian666
{
    public partial class Ccli
    {
        // 替换控制台输出
        static Ccli() => Console.SetOut(new SocketStringWriter(Console.Out));

        // 接管控制台输出,转发到套接字
        class SocketStringWriter : TextWriter
        {
            private readonly TextWriter _out;

            public SocketStringWriter(TextWriter @out) => _out = @out;

            public override Encoding Encoding => _out.Encoding;
            public override void Write(char value)
            {
                _out.Write(value);
                _socket?.Send(value.ToString());
            }

            public override void Write(char[] buffer, int index, int count)
            {
                _out.Write(buffer, index, count);
                _socket?.Send(new string(buffer, index, count));
            }

            public override void Write(string? value)
            {
                if (value != null)
                {
                    _out.Write(value);
                    _socket?.Send(value);
                }
            }

            public override void WriteLine(string? value)
            {
                if (value != null)
                {
                    _out.WriteLine(value);
                    _socket?.Send("> " + value + "\n");
                }
            }
        }
    }
}
